package com.yfbao.horizon.compress;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KryoSerialization {
    private static Kryo kryo = new Kryo();
    static {
        init();
    }
    // 将对象序列化为字节数组
    public static byte[] serializeObject(Object obj) {
//        Class<?> aClass = obj.getClass();
//        kryo.register(aClass);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Output output = new Output(bos);
        kryo.writeClassAndObject(output, obj);
        output.close();
        return bos.toByteArray();
    }

    // 将字节数组反序列化为对象
    public static Object deserializeObject(byte[] data) {
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        Input input = new Input(bis);
        Object obj = kryo.readClassAndObject(input);
        input.close();
        return obj;
    }

    public static void init(){
        kryo.register(java.util.HashMap.class);
        kryo.register(java.util.ArrayList.class);
        kryo.register(CtpEntityResource.class);
//        kryo.getRegistration()
    }

    public static void main(String[] args) throws IOException {
        init();
        // 创建一个 Person 对象
        Map<String,Object> map =new HashMap<>();
        List<String> list =new ArrayList<>();
        list.add("14737506170");
        list.add("18435088260");
        map.put("aaaaa",list);
        // 将 Person 对象序列化为字节数组
        byte[] serializedData = serializeObject(map);

        // 将字节数组反序列化为对象
        Map deserializedPerson = (Map<String,Object>) deserializeObject(serializedData);

        Object aaaaa = map.get("aaaaa");
        System.out.println(aaaaa);
        // 输出反序列化后的对象
        System.out.println("Deserialized Person: " + deserializedPerson);
    }
}
